import { Material } from "../../dto/material";
import { getTableRecordsSearch } from "../../infra/BitableUtils";
import { FeiShuTable } from "../../infra/util/TableUtils";
import { Condition, Filter, FSBitableQuery, QUERTY_CONJUNCTION, QUERTY_OPERATOR } from "../../infra/queryObj/ConditionalBitableQuery";

/* 
用于中药材的keyword判断
*/
function judgeKeyword(keyword: string | null) {
   if (keyword == null || keyword == "" || keyword == undefined) {
      return {};
   } else {
      const condition: Condition = {
         field_name : "name",
         operator : QUERTY_OPERATOR.LIKE,
         value : [keyword]
      }
      const temFilter: Filter = {
         conditions: [condition],
         conjunction: QUERTY_CONJUNCTION.AND
      }
      const query: FSBitableQuery = {
         field_names: ["id", "name", "description", "feature"],
         filter: temFilter
      }
      return query;
   }

}

/* 
加工获取到的date数据 
*/
export function materialProcess(items: any[]) {
   const result: Material[] = [];
   for (let i = 0; i < items.length; i++) {
      const item = items[i].fields;
      const material: Material = {
         id: item.id,
         name: item.name[0].text,
         description: item.description[0].text,
         feature: item.feature[0].text
      }
      result.push(material);
   }
   return result;
}

/* 
获取所有的药材接口
*/
export async function getAllMaterials(condition: string | null) {
   const query = judgeKeyword(condition);
   let result = await getTableRecordsSearch(FeiShuTable.Material, query, `page_size=500`)
   let isMore: boolean = result.has_more;
   while (isMore) {
      let tem = await getTableRecordsSearch(FeiShuTable.Material, query, `page_token=${result.page_token}&page_size=500`)
      result.items.push(...tem.items);
      isMore = tem.has_more;
   }
   return result;
}